package com.itheima.dao;

import com.itheima.bean.Menu;
import com.itheima.bean.Restaurant;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class RestaurantDaoImpl implements RestaurantDao{
    private static String restaurantFilePath = "take-away-system/src/com/itheima/data/restaurants.oxt";

    @Override
    public Restaurant browseRestaurant(String name) throws Exception {
        final List<Restaurant> restaurants = browseRestaurants();
        for (Restaurant restaurant : restaurants) {
            if (name.equals(restaurant.getName())) {
                return restaurant;
            }
        }
        return null;
    }

    @Override
    public List<Restaurant> browseRestaurants() throws IOException {
        try {
            // 1. 序列流读取
            final ObjectInputStream ois = new ObjectInputStream(new FileInputStream(restaurantFilePath));

            // 2. 读取
            final List<Restaurant> restaurants = (List<Restaurant>) ois.readObject();

            // 3. 关闭流
            ois.close();

            return restaurants;
        } catch (FileNotFoundException e) {
            // 没找到文件，先创建个空列表写进去
            List<Restaurant> restaurants = new ArrayList<>();
            saveRestaurantsList(restaurants);
            return restaurants;
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
            List<Restaurant> restaurants = new ArrayList<>();
            return restaurants;
        }
    }

    @Override
    public List<Restaurant> addRestaurant(String name, List<Menu> menuList) throws Exception {
        try {
            // 1. 新建餐厅
            final Restaurant restaurantNew = new Restaurant(name);
            restaurantNew.setMenuList(menuList);

            // 2. 获取所有餐厅
            final List<Restaurant> restaurants = browseRestaurants();

            // 3. 添加到列表
            // 判断是否已存在
            final int index = restaurants.indexOf(restaurantNew);
            if (index > -1) {
                restaurants.set(index, restaurantNew);
            } else {
                restaurants.add(restaurantNew);
            }

            // 4. 保存到文件
            saveRestaurantsList(restaurants);

            return restaurants;
        } catch (Exception e) {
            e.printStackTrace();
            return browseRestaurants();
        }
    }

    // 保存列表到文件
    public void saveRestaurantsList(List<Restaurant> restaurants) throws IOException {
        // 1. 序列流读取
        final ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(restaurantFilePath));

        // 2. 写入
        oos.writeObject(restaurants);

        // 3. 关闭流
        oos.close();
    }
}
